package cc.chenwenxi.sdk.api;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.httpclient.HttpsURL;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cc.chenwenxi.sdk.rainbow.FanKit;
import cc.chenwenxi.sdk.rainbow.OledKit;
import cc.chenwenxi.sdk.rainbow.RgbKit;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import javazoom.jl.player.Player;
import jodd.io.StreamUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api")
public class ApiController {

	@GetMapping("/fan/{speed}")
	public void fan(@PathVariable("speed") Integer speed) {
		new FanKit().speed(speed);
		log.info("风扇转速:{}", speed);
	}

	@GetMapping("/rgb/{name}")
	public void rgb(@PathVariable("name") String name) {
		log.info("rgb:{}", name);
		String[] split = name.split(",");
		int r = Convert.toInt(split[0]);
		int g = Convert.toInt(split[1]);
		int b = Convert.toInt(split[2]);
		RgbKit rgb = new RgbKit();
		rgb.setRgb(new RgbKit.Rgb(r, g, b));

		ThreadUtil.sleep(1000 * 3);
		log.info("关闭rgb");
		rgb.shutdown();
	}

	@GetMapping("/oled/{name}")
	public void oled(@PathVariable("name") String name) {
		log.info("要打印的字:{}", name);
		OledKit oled = new OledKit(0, 0);
		oled.text(name);
	}
	
	@GetMapping("/oledup")
	public void oledStartup() {
		OledKit oled = new OledKit(0, 0);
		oled.start();
		log.info("屏幕启动");
	}
	
	@GetMapping("/oleddown")
	public void oleddown() {
		OledKit oled = new OledKit(0, 0);
		oled.shutdown();
		log.info("屏幕关闭");
	}
	

	@GetMapping("/music")
	public void music() {
		try {
//			String path = "/home/music/生僻字.mp3";
//			BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(path));
			String url ="http://tsn.baidu.com/text2audio?tok=24.2a2ac7ece827ef700ee827d9e5b1185d.2592000.1558450800.282335-7828085&cuid=123456&tex=%E7%9C%9F%E7%9A%84%E5%93%8E%E5%91%80,%E5%B7%B2%E7%BB%8F%E6%88%90%E5%8A%9F%E4%BA%A4%E6%98%93%E4%BA%860.01%E4%B8%AA%E6%AF%94%E7%89%B9%E5%B8%81&lan=zh&pit=6&per=4&ctp=1";
			InputStream stream = URLUtil.getStream(new URL(url));
			BufferedInputStream buffer = new BufferedInputStream(stream);
			Player player = new Player(buffer);
			player.play();
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}
